package btp.CoordinateSystems;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import btp.Time.SiderealTime;
import btp.Time.Time;
import btp.Trigonometry.Angle;


public class EclipticCoordinate {

	double eclipticLongitude;
	double eclipticLatitude;

	public EclipticCoordinate(double eclipticLatitude, double eclipticLongitude) {
		this.eclipticLatitude=eclipticLatitude;
		this.eclipticLongitude=eclipticLongitude;
	}

	public static EclipticCoordinate getEclipticFromEquatorial(EquatorialCoordinate e)
	{
		double alpha = e.rightAscension.toDouble()*360;
		double sinalpha = Math.sin(alpha);
		double cosalpha = Math.cos(alpha);
		double sindelta = Math.sin(e.declination);
		double cosdelta = Math.cos(e.declination);
		double cosepsilon = Math.cos(getObliquity().toDouble());
		double sinepsilon = Math.sqrt(getObliquity().toDouble());
		double eclipticLongitude = Math.atan((sinalpha*cosalpha + sindelta*sinepsilon/cosdelta)/cosalpha);
		double eclipticLatitude = Math.asin(sindelta*cosepsilon - cosdelta*sinalpha);
		return new EclipticCoordinate(eclipticLatitude, eclipticLongitude);
	}
	
	public EquatorialCoordinate getEquatorialFromEcliptic(){
		double sinlambda = Math.sin(eclipticLongitude);
		double coslambda = Math.cos(eclipticLongitude);
		double sinbeta = Math.sin(eclipticLatitude);
		double cosbeta = Math.cos(eclipticLatitude);
		double cosepsilon = Math.cos(getObliquity().toDouble());
		double sinepsilon = Math.sqrt(getObliquity().toDouble());
		return new EquatorialCoordinate((SiderealTime) Time.fromDouble(Math.atan((sinlambda*cosepsilon-sinbeta*sinepsilon/cosbeta)/coslambda)),Math.asin(sinbeta*cosepsilon+cosbeta*sinepsilon*sinlambda));
	}


	static long lastUpdate=0;
	static Angle obliquity;
	static final long  periodForUpdate = 86000*365*10; //about 10 years 
	public static Angle getObliquity(){
		if(Math.abs(lastUpdate-new Date().getTime())<periodForUpdate)
			return obliquity;
		Calendar cal = new GregorianCalendar();
		//Should get it from the applications own current time.
		return getObliquity(cal.get(Calendar.YEAR));
	}

	public static Angle getObliquity(int year){
		double t=(year-2000)/10000;
		double [] coeffs ={-4680.93,1.55,1999.25,51.38, 249.67, 39.05, 7.12, 27.87, 5.79, 2.45};
		double seconds = 0;
		for(int i=1; i<=10; i++)
		{
			seconds += coeffs[i]*t;
			year*=t;
		}
		seconds += 21.448;
		int minutes = (int) Math.floor(seconds/60.0);
		seconds -= minutes*60;
		minutes += 26;
		return new Angle(23, minutes, seconds);
	}


}
